package org.libermundi.theorcs.security.services.impl;

import javax.sql.DataSource;

import org.libermundi.theorcs.core.util.IOHelper;
import org.libermundi.theorcs.security.exception.UnsupportedAclDatabaseException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.Assert;

public class AclDatabaseSchemaAndDataPopulator implements InitializingBean {
    private JdbcTemplate _jdbcTemplate;
    private TransactionTemplate _transactionTemplate;	
    private String _hibernateDialect;	

	@Override
	public void afterPropertiesSet() throws Exception {
        Assert.notNull(_jdbcTemplate, "dataSource required");
        Assert.notNull(_transactionTemplate, "platformTransactionManager required");
        Assert.notNull(_hibernateDialect, "hibernateDialect required");

        //Do we need to create the Database ?
        try {
        	_jdbcTemplate.execute("Select 1 from acl_sid");
		} catch (Exception e) {
			createTables();
		}
        
	}
	
	private void createTables() throws UnsupportedAclDatabaseException {
        String createSqlScript = null;
        Assert.notNull(_hibernateDialect);
        
        if(_hibernateDialect.equals("org.hibernate.dialect.MySQL5InnoDBDialect")) {
        	createSqlScript = IOHelper.readFileFromClasspath("/META-INF/sql/create/mysql-innodb.sql");
        } else if(_hibernateDialect.equals("org.hibernate.dialect.HSQLDialect")) {
        	createSqlScript = IOHelper.readFileFromClasspath("/META-INF/sql/create/hsqldb.sql");
        }
        
        if(createSqlScript == null) {
        	throw new UnsupportedAclDatabaseException(String.format("The Database corresponding to the Dialect '%s' is not supported for Acl",	_hibernateDialect));
        }
        
        // create schema to allow Spring Security ACL approach.
        String[] sql = createSqlScript.split(";");
        for (int i = 0; i < sql.length; i++) {
        	if(sql[i].trim().length() > 0) {
        		_jdbcTemplate.execute(sql[i]);
        	}
		}
	}


	// Setters
	public void setDataSource(final DataSource datasource) {
		_jdbcTemplate = new JdbcTemplate(datasource);
	}

	public void setPlatformTransactionManager(final PlatformTransactionManager platformTransactionManager) {
		_transactionTemplate = new TransactionTemplate(platformTransactionManager);
    }

	public void setHibernateDialect(String hibernateDialect) {
		_hibernateDialect = hibernateDialect;
	}

}
